package com.ppp.poi.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.ppp.poi.bean.entity.User;
import com.ppp.poi.common.AppConstant;
import com.ppp.poi.common.exception.AppSimpleException;
import com.ppp.poi.service.UserService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author Wu Jin
 * @create 2020-01-19
 */
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

  @Autowired
  private UserService userService;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    String token = request.getHeader("token");
    log.info("token={}", token);
    User user = userService.getByToken(token);
    log.info("user={}", JSON.toJSON(user));
    if (user == null) {
      throw new AppSimpleException(401, "请先登录");
    } else {
      AppConstant.add("user", user);
    }
    return true;
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    AppConstant.remove();
  }
}
